package com.mszlu.blog.controller;

import com.mszlu.blog.dao.pojo.FileSuccess;
import com.mszlu.blog.utils.QiniuUtils;
import com.mszlu.blog.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("upload")
public class UploadController {

    @Autowired
    private QiniuUtils qiniuUtils;
    @Value("${spring.hadoop.fsUri}")
    private String urlPost;

    FileSystem fileSystem = null;

    @PostMapping
    public Result upload(@RequestParam("image") MultipartFile file){
        //原始文件名称 比如 aa.png
        String originalFilename = file.getOriginalFilename();
        //唯一的文件名称
        String fileName = UUID.randomUUID().toString() + "." + StringUtils.substringAfterLast(originalFilename, ".");
        //上传文件 上传到哪呢？ 七牛云 云服务器 按量付费 速度快 把图片发放到离用户最近的服务器上
        // 降低 我们自身应用服务器的带宽消耗

        boolean upload = qiniuUtils.upload(file, fileName);
        if (upload){
            return Result.success(QiniuUtils.qiniu_img_url_pre + fileName);
        }
        return Result.fail(20001,"上传失败");
    }

    /**
     *
     * @param file
     * @param req
     * @return
     * @throws IOException
     * @throws URISyntaxException
     * @throws InterruptedException
     */
    @PostMapping("/file")
    public List<FileSuccess> uploadFile(@RequestParam("image") MultipartFile file, HttpServletRequest req) throws IOException, URISyntaxException, InterruptedException {
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd");
        String format = sdf.format(new Date());
        String realPath = req.getServletContext().getRealPath("/upload") + format + "/" ;
        File folder = new File(realPath);
        System.out.println("-------------"+realPath+"----------------");
        if (!folder.exists()){
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = oldName;
        file.transferTo(new File(folder,newName));
        String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/upload" + format +"/"+ newName;
        System.out.println("本地文件路径"+url);
        String filePath = realPath+"\\"+newName;
        System.out.println("hdfs" + urlPost);
        fileSystem = FileSystem.get(new URI(urlPost), new Configuration(), "root");
        // 创建输入流，参数指定文件输出地址

        InputStream in = new FileInputStream(filePath);

        // 调用create方法指定文件上传，参数HDFS上传路径
        OutputStream out = fileSystem.create(new Path("/" + newName));
        // 使用Hadoop提供的IOUtils，将in的内容copy到out，设置buffSize大小，是否关闭流设置true
        IOUtils.copyBytes(in, out, 4096, true);
        System.out.println("文件路径" + filePath);
        System.out.println("real" + realPath);
        System.out.println("上传到Hadoop上的url是"+url);
        List<FileSuccess> map = new ArrayList<>();
        FileSuccess fileSuccess = new FileSuccess();
        fileSuccess.setFilename(newName);
        fileSuccess.setUrl(url);
        map.add(fileSuccess);
        return map;
    }
}
